package com.twan.kotlinbase.fragment

import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import butterknife.OnClick
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.blankj.utilcode.util.ToastUtils
import com.tencent.qcloud.tim.demo.login.UserInfo
import com.tencent.qcloud.tim.demo.utils.DemoLog
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.utils.ToastUtil
import com.twan.kotlinbase.R
import com.twan.kotlinbase.app.BaseDataBindingFragment
import com.twan.kotlinbase.bean.LoginBean
import com.twan.kotlinbase.databinding.FragmentLoginBinding
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.ui.MainActivity
import com.twan.kotlinbase.util.InputUtils
import com.twan.kotlinbase.util.JsonUtil
import com.twan.kotlinbase.util.MyUtils
import com.twan.kotlinbase.widgets.router.Router
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.android.synthetic.main.fragment_login.edt_code
import kotlinx.android.synthetic.main.fragment_login.edt_mobile
import kotlinx.android.synthetic.main.fragment_login.edt_password
import kotlinx.android.synthetic.main.fragment_login.tv_verfiy
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

class LoginFragment: BaseDataBindingFragment<FragmentLoginBinding>() {

    override fun getLayoutId(): Int {
        return R.layout.fragment_login
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        title?.text = ""//resources.getText(R.string.tab3)
        back?.visibility=View.GONE
        mBinding.isMobileLogin=false
    }

    @OnClick(R.id.rl_other_login)
    fun otherLogin(){
        mBinding.isMobileLogin=!mBinding.isMobileLogin!!
    }

    @OnClick(R.id.btn_login)
    fun login(){
        RxHttpScope().launch {
            var req = if (mBinding.isMobileLogin!!){
                if (!InputUtils.checkEmpty(edt_mobile,edt_code)) return@launch
                RxHttp.postJson("users/loginByPhone")
                        .add("code",edt_code.text.toString())
                        .add("mobile",edt_mobile.text.toString())
                        .add("type",1)
                        .toResponse<LoginBean>()
                        .await()
            } else {
                if (!InputUtils.checkEmpty(edt_account,edt_password)) return@launch
                RxHttp.postJson("users/loginByUserName")
                        .add("userName",edt_account.text.toString())
                        .add("password",edt_password.text.toString())
                        .toResponse<LoginBean>()
                        .await()
            }
            SPUtils.getInstance().put("token",req.token)
            SPUtils.getInstance().put("personinfo", JsonUtil.objectToJson(req))
            loginIM();
        }

    }

    private fun loginIM() {
        RxHttpScope().launch {
            val kefuid = if (MyUtils.isLogin()) MyUtils.getUserid() else "小肚驴游客"
//                val userSig = GenerateTestUserSig.genTestUserSig(kefuid)
            val userSig =  RxHttp.get("im/generateUserSig")
                .add("userId", MyUtils.getUserid())
                .toResponse<Any>().await()


            TUIKit.login(kefuid, userSig as String?, object : IUIKitCallBack {
                override fun onError(module: String, code: Int, desc: String) {
                    runOnUiThread { ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc) }
                    DemoLog.i("ssssssssss", "imLogin errorCode = $code, errorInfo = $desc")
                    goMain();
                }

                override fun onSuccess(data: Any?) {
                    UserInfo.getInstance().setAutoLogin(true)
                    LogUtils.e("登录成功")
                    goMain();
                }
            })
        }
    }

    private fun goMain() {
        Router.newIntent(mActivity).to(MainActivity::class.java).launch()
        mActivity!!.finish()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(event: String){

    }

    @OnClick(R.id.tv_verfiy)
    fun verfiy(){
        timer()
    }



    private var timer: CountDownTimer? = null
    private fun timer() {
        if (!InputUtils.checkEmpty(edt_mobile)){ return }
        LogUtils.e("手机号:${edt_mobile.text.toString()}")
        RxHttpScope().launch {
            val req = RxHttp.postJson("/sms/send")
                    .add("mobile", edt_mobile.text.toString())
                    .add("type", 1)
                    .toResponse<Any>().await()

            ToastUtils.showShort("验证码发送成功")

            timer = object : CountDownTimer(60000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    tv_verfiy.isClickable = false
                    tv_verfiy.text = millisUntilFinished.div(1000).toString() + "s"
                }

                override fun onFinish() {
                    tv_verfiy.isClickable = true
                    tv_verfiy.text = "获取验证码"
                }
            }
            timer!!.start()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer!!.cancel()
        }
    }
}